package com.jz.digital.warehousing

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.text.InputType
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.PopupWindow
import com.jz.digital.R
import com.jz.digital.base.BaseActivity
import com.jz.digital.bean.ServerBean
import com.jz.digital.dialog.DialogUtil
import com.jz.digital.scan.ScanCodeActivity
import com.jz.digital.utils.DataUtil
import com.jz.digital.utils.systembar.ImmersionBar
import kotlinx.android.synthetic.main.activity_production_warehousing.label_bottom_buliang_yuanying
import kotlinx.android.synthetic.main.activity_production_warehousing.label_buliang_shuliang
import kotlinx.android.synthetic.main.activity_production_warehousing.label_gong_dan
import kotlinx.android.synthetic.main.activity_production_warehousing.label_gong_dan_liang
import kotlinx.android.synthetic.main.activity_production_warehousing.label_gui_ge
import kotlinx.android.synthetic.main.activity_production_warehousing.label_ke_hu
import kotlinx.android.synthetic.main.activity_production_warehousing.label_label
import kotlinx.android.synthetic.main.activity_production_warehousing.label_liangpin_shuliang
import kotlinx.android.synthetic.main.activity_production_warehousing.label_liao_hao
import kotlinx.android.synthetic.main.activity_production_warehousing.label_pin_ming
import kotlinx.android.synthetic.main.activity_production_warehousing.label_po
import kotlinx.android.synthetic.main.activity_production_warehousing.label_scan
import kotlinx.android.synthetic.main.activity_production_warehousing.sv_parent
import kotlinx.android.synthetic.main.activity_production_warehousing.tv_commit
import kotlinx.android.synthetic.main.activity_production_warehousing_pre_layout.cml_ban_zu
import kotlinx.android.synthetic.main.activity_production_warehousing_pre_layout.cml_cang_bie
import kotlinx.android.synthetic.main.layout_common_title.layout_parent

/**
 * @author WangYong
 * @date 2024/11/28 13:28
 * @description:生产入库
 */
class ProductionWarehousingActivity : BaseActivity<ProductionWarehousingPresenter>(),
    IProductionWarehousingView, View.OnClickListener {
    private var mBanZuPopupWindow: PopupWindow? = null
    private var mCangBiePopupWindow: PopupWindow? = null
    private var mTeamGroupPopupWindow: PopupWindow? = null

    /**
     * 整套
     */
    private var mCompletePopupWindow: PopupWindow? = null
    private lateinit var mCompleteList: MutableList<ServerBean.GXInfo>

    /**
     * 工单输入框焦点
     */
    private var mOrderEditFocus = false
    private var mNo7 = ""
    private var mNo8 = ""
    private var mNo10 = ""

    override fun getLayoutResId(): Int {
        return R.layout.activity_production_warehousing
    }

    override fun initData() {
        super.initData()
        mCompleteList = mutableListOf(
            ServerBean.GXInfo(basId = "Y", basName = getText(R.string.text_yes).toString()),
            ServerBean.GXInfo(basId = "N", basName = getText(R.string.text_no).toString())
        )
        mPresenter.initData()
    }

    override fun initViews() {
        super.initViews()
        ImmersionBar.with(this).statusBarColor(R.color.main_color)
            .titleBarMarginTop(layout_parent)
            .init()
        setTitle(R.string.finished_product_warehousing)
        mTitleBar.getTitleLayoutAll(this).setBackgroundColor(getColor(R.color.main_color))
        mTitleBar.setLeftImgTint(ColorStateList.valueOf(Color.WHITE))
        mTitleBar.setTitleColor(Color.WHITE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == scanRequestCode) {
            label_scan?.getEditWidget()
                ?.setText(data?.getStringExtra(ScanCodeActivity.KEY_DATA) ?: "")

            commit()
        }
    }

    private fun commit(isCommit: Boolean = false) {
        if (label_scan?.getEditWidget()?.text?.toString().isNullOrEmpty()) return
        mPresenter.commit(
            barcode = label_scan?.getEditWidget()?.text?.toString() ?: "",
            no1 = label_gong_dan?.getContentWidget()?.text?.toString() ?: "",
            no9 = label_bottom_buliang_yuanying?.getEditText() ?: "",
            no7 = mNo7,
            no8 = mNo8,
            no10 = mNo10,
            DataUtil.toInt(
                label_liangpin_shuliang?.getEditText() ?: ""
            ),
            DataUtil.toInt(
                label_label?.getEditText() ?: ""
            ),
            DataUtil.toInt(
                label_buliang_shuliang?.getEditText() ?: ""
            ), label_po?.getEditText() ?: "", isCommit
        )
    }

    override fun initListening() {
        super.initListening()
        label_liangpin_shuliang?.getEditWidget()?.inputType = InputType.TYPE_CLASS_NUMBER
        label_buliang_shuliang?.getEditWidget()?.inputType = InputType.TYPE_CLASS_NUMBER
        cml_ban_zu.setOnClickListener(this)
        cml_cang_bie.setOnClickListener(this)
        label_ke_hu.setOnClickListener(this)
        tv_commit.setOnClickListener(this)
        label_bottom_buliang_yuanying?.getRightImage()?.setOnClickListener(this)
        label_scan?.getRightImage()?.setOnClickListener {
            clearShowContent()
            startActivityForResult(
                Intent(this@ProductionWarehousingActivity, ScanCodeActivity::class.java),
                scanRequestCode
            )
        }
        label_scan?.getEditWidget()?.gravity = Gravity.END
        label_scan?.getEditWidget()?.onFocusChangeListener =
            View.OnFocusChangeListener { p0, p1 ->
                mOrderEditFocus = p1
                if (!p1) {
                    commit()
                } else {
                    clearBackContent()
                }
            }
        // 处理 ScrollView 的触摸事件，使 EditText 失去焦点
        sv_parent.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_MOVE) {
                // 隐藏软键盘并清除 EditText 焦点
                if (mOrderEditFocus) {
                    label_scan?.getEditWidget()?.clearFocus()
                }
            }
            false
        }
         label_liangpin_shuliang?.getEditWidget()?.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                label_liangpin_shuliang?.getEditWidget()?.setText("")
            }
        }
        label_buliang_shuliang?.getEditWidget()?.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                label_buliang_shuliang?.getEditWidget()?.postDelayed({
                    label_buliang_shuliang?.getEditWidget()
                        ?.setSelection(label_buliang_shuliang?.getEditWidget()?.text?.length ?: 0)
                }, 100)
            }
        }
    }

    companion object {
        const val scanRequestCode = 100

        @JvmStatic
        fun startActivity(context: Context) {
            context.startActivity(Intent(context, ProductionWarehousingActivity::class.java))
        }
    }

    override fun showLoading() {
        showLoadingDialog()
    }

    override fun dismissLoading() {
        dismissLoadingDialog(true)
    }

    @SuppressLint("SetTextI18n")
    override fun reportSuccess(data: ServerBean.RuKuResponse, isCommit: Boolean) {
        if (isCommit) {
            showToast(getString(R.string.commit_success))
            clearShowContent()
            return
        }
        label_gong_dan?.getContentWidget()?.text = data.no1
        label_ke_hu?.getContentWidget()?.text = data.no2
        label_po?.getContentWidget()?.text = data.no6
        label_liao_hao?.getContentWidget()?.text = data.no5
        label_pin_ming?.getContentWidget()?.text = data.no3
        label_gui_ge?.getContentWidget()?.text = data.no4
        label_liangpin_shuliang?.getEditWidget()?.setText(data.qty2.toString())
        label_gong_dan_liang?.getContentWidget()?.text = data.qty1.toString()
        label_label?.getEditWidget()?.setText(data.qty3.toString())
        label_buliang_shuliang?.getEditWidget()?.setText(data.qty4.toString())
        label_bottom_buliang_yuanying?.getEditWidget()?.setText(data.no9)
    }

    /**
     * 清除显示内容
     */
    private fun clearShowContent() {
        label_scan?.getEditWidget()?.clearFocus()
        label_liangpin_shuliang?.getEditWidget()?.clearFocus()
        label_label?.getEditWidget()?.clearFocus()
        label_buliang_shuliang?.getEditWidget()?.clearFocus()
        clearBackContent()

    }

    /**
     * 清除返回内容
     */
    private fun clearBackContent(){
        label_scan?.getEditWidget()?.setText("")
        label_gong_dan?.getContentWidget()?.text = ""
        label_ke_hu?.getContentWidget()?.text = ""
        label_po?.getContentWidget()?.text = ""
        label_liao_hao?.getContentWidget()?.text = ""
        label_pin_ming?.getContentWidget()?.text = ""
        label_gui_ge?.getContentWidget()?.text = ""
        label_liangpin_shuliang?.getEditWidget()?.setText("")
        label_gong_dan_liang?.getContentWidget()?.text = ""
        label_label?.getEditWidget()?.setText("")
        label_buliang_shuliang?.getEditWidget()?.setText("")
        label_bottom_buliang_yuanying?.getEditWidget()?.setText("")
    }

    override fun reportFailed(isCommit: Boolean, message: String?) {
        showToast(
            if (message.isNullOrEmpty()) (if (isCommit) getString(R.string.commit_failed) else getString(
                R.string.request_failed
            )) else message
        )
    }

    private fun showBanZuDialog() {
        if (mBanZuPopupWindow?.isShowing == true) {
            return
        }
        if (mBanZuPopupWindow == null) {
            mBanZuPopupWindow = getNormalPopupWindow(mPresenter.mBanZuList) {
                mNo7 = mPresenter.mBanZuList[it].basId ?: ""
                cml_ban_zu?.getContentWidget()?.text = mPresenter.mBanZuList[it].basName
                mBanZuPopupWindow?.dismiss()
            }
        }
        mBanZuPopupWindow?.showAsDropDown(
            cml_ban_zu.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    private fun showCangBieDialog() {
        if (mCangBiePopupWindow?.isShowing == true) {
            return
        }
        if (mCangBiePopupWindow == null) {
            mCangBiePopupWindow = getNormalPopupWindow(mPresenter.mCangBieList) {
                mNo8 = mPresenter.mCangBieList[it].basId ?: ""
                cml_cang_bie?.getContentWidget()?.text = mPresenter.mCangBieList[it].basName
                mCangBiePopupWindow?.dismiss()
            }
        }
        mCangBiePopupWindow?.showAsDropDown(
            cml_cang_bie.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    /**
     * 是否整套
     */
    private fun showCompleteDialog() {
        if (mCompletePopupWindow?.isShowing == true) {
            return
        }
        if (mCompletePopupWindow == null) {
            mCompletePopupWindow = getNormalPopupWindow(mCompleteList) {
                mNo10 = mCompleteList[it].basId ?: "Y"
                label_ke_hu?.getContentWidget()?.text = mCompleteList[it].basName
                mCompletePopupWindow?.dismiss()
            }
        }
        mCompletePopupWindow?.showAsDropDown(
            label_ke_hu.getContentWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    private fun showBuLiangDialog() {
        if (mTeamGroupPopupWindow?.isShowing == true) {
            return
        }
        if (mTeamGroupPopupWindow == null) {
            mTeamGroupPopupWindow = getNormalPopupWindow(mPresenter.mBuLiangList) {
                label_bottom_buliang_yuanying?.getEditWidget()
                    ?.setText(mPresenter.mBuLiangList[it].basName)
                mTeamGroupPopupWindow?.dismiss()
            }
        }
        mTeamGroupPopupWindow?.showAsDropDown(
            label_bottom_buliang_yuanying.getEditWidget(),
            0,
            0,
            Gravity.BOTTOM.or(Gravity.END)
        )
    }

    override fun onBuLiangSuccess() {
        showBuLiangDialog()
    }

    private fun getNormalPopupWindow(
        dataList: List<ServerBean.GXInfo>,
        callback: (index: Int) -> Unit
    ): PopupWindow {
        return DialogUtil.getNormalPop(this, dataList, callback)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.cml_ban_zu -> {
                //班组
                showBanZuDialog()
            }

            R.id.cml_cang_bie -> {
                //仓别
                showCangBieDialog()
            }

            R.id.label_ke_hu -> {
                //是否整套
                showCompleteDialog()
            }

            //不良原因
            R.id.img_right -> {
                mPresenter.getBuLiangFromServer()
            }

            R.id.tv_commit -> {
                if (label_liangpin_shuliang?.getEditText().isNullOrEmpty()) {
                    showToast(R.string.input_liangpin_num)
                    return
                }
                if (DataUtil.toInt(label_liangpin_shuliang?.getEditText()) < 0) {
                    showToast(R.string.the_quantity_cannot_be_negative)
                    return
                }
                if (DataUtil.toInt(label_buliang_shuliang?.getEditText()) < 0) {
                    showToast(R.string.the_number_of_defects_cannot_be_negative)
                    return
                }
                //提交
                if (DataUtil.toInt(
                        label_buliang_shuliang?.getEditWidget()?.text?.trim().toString()
                    ) > 0 && (label_bottom_buliang_yuanying?.getEditWidget()?.text?.toString()
                        ?: "").isEmpty()
                ) {
                    showToast(R.string.please_input_reson)
                    return
                }
                commit(true)
            }
        }
    }
}